using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class KeyboardHook : MonoBehaviour
{
    [UnmanagedFunctionPointer(CallingConvention.StdCall)]
    public delegate void KeyCallback(int vkCode);
    
    [DllImport("UnityDLL.dll")]
    private static extern bool InstallHook(IntPtr hWnd, KeyCallback callback);
    [DllImport("UnityDLL.dll")]
    private static extern void UninstallHook();
    
    private static KeyCallback callbackDelegate;
    private IntPtr _hwnd;
    public TextMeshProUGUI numberText; 
    public TextMeshProUGUI vkText; 
    private int num = 0;
    public FrameAnimationController frameAnimationController; // 帧动画控制器引用

        
    [Header("移动设置")]
    public float moveSpeed = 50f; // 每次按键的移动距离（像素）
    public float minMoveSpeed = 20f; // 最小移动速度
    public float maxMoveSpeed = 100f; // 最大移动速度
    public bool adaptiveSpeed = true; // 是否根据打字速度自适应移动速度
    public bool enableImageMovement = true; // 是否启用帧动画
    
    public Image movingImage; 
    private RectTransform imageRectTransform; // Image的RectTransform组件
    private Canvas parentCanvas; // 父级Canvas
    private float canvasWidth; // Canvas宽度
    private float lastKeyPressTime; // 上次按键时间
    private float currentSpeed; // 当前移动速度
    
    
    // 虚拟键码到按键名称的映射字典
    private static readonly Dictionary<int, string> KeyCodeNames = new Dictionary<int, string>
    {
        // 数字键
        { 48, "0" }, { 49, "1" }, { 50, "2" }, { 51, "3" }, { 52, "4" },
        { 53, "5" }, { 54, "6" }, { 55, "7" }, { 56, "8" }, { 57, "9" },
        
        // 字母键
        { 65, "A" }, { 66, "B" }, { 67, "C" }, { 68, "D" }, { 69, "E" },
        { 70, "F" }, { 71, "G" }, { 72, "H" }, { 73, "I" }, { 74, "J" },
        { 75, "K" }, { 76, "L" }, { 77, "M" }, { 78, "N" }, { 79, "O" },
        { 80, "P" }, { 81, "Q" }, { 82, "R" }, { 83, "S" }, { 84, "T" },
        { 85, "U" }, { 86, "V" }, { 87, "W" }, { 88, "X" }, { 89, "Y" },
        { 90, "Z" },
        
        // 功能键
        { 112, "F1" }, { 113, "F2" }, { 114, "F3" }, { 115, "F4" },
        { 116, "F5" }, { 117, "F6" }, { 118, "F7" }, { 119, "F8" },
        { 120, "F9" }, { 121, "F10" }, { 122, "F11" }, { 123, "F12" },
        
        // 特殊键
        { 8, "Backspace" }, { 9, "Tab" }, { 13, "Enter" }, { 16, "Shift" },
        { 17, "Ctrl" }, { 18, "Alt" }, { 19, "Pause" }, { 20, "Caps Lock" },
        { 27, "Escape" }, { 32, "Space" }, { 33, "Page Up" }, { 34, "Page Down" },
        { 35, "End" }, { 36, "Home" }, { 37, "Left Arrow" }, { 38, "Up Arrow" },
        { 39, "Right Arrow" }, { 40, "Down Arrow" }, { 45, "Insert" }, { 46, "Delete" },
        { 160, "Left Shift"}, { 161, "Right Shift"}, { 162, "Left Ctrl"}, { 163, "Right Ctrl"},
        { 91, "Win"},{ 164, "Left Alt"}, { 165, "Right Alt"}, 
        // 符号键
        { 186, ";" }, { 187, "=" }, { 188, "," }, { 189, "-" }, { 190, "." },
        { 191, "/" }, { 192, "`" }, { 219, "[" }, { 220, "\\" }, { 221, "]" },
        { 222, "'" },
        
        // 小键盘
        { 96, "Num 0" }, { 97, "Num 1" }, { 98, "Num 2" }, { 99, "Num 3" },
        { 100, "Num 4" }, { 101, "Num 5" }, { 102, "Num 6" }, { 103, "Num 7" },
        { 104, "Num 8" }, { 105, "Num 9" }, { 106, "Num *" }, { 107, "Num +" },
        { 109, "Num -" }, { 110, "Num ." }, { 111, "Num /" },
        
        // 鼠标按键
        { 1, "Left Mouse" }, { 2, "Right Mouse" }, { 4, "Middle Mouse" }
    };

    private void Awake()
    {
        _hwnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
        callbackDelegate = OnKeyPressed;
        bool result = InstallHook(_hwnd, callbackDelegate);
        
        if (!result)
            Debug.LogError("钩子安装失败！");
        else
            Debug.Log("钩子安装成功！");
    }

    void Start()
    {
        GameObject numberObj = GameObject.Find("Nums");
        if (numberObj != null)
        {
            numberText = numberObj.GetComponent<TextMeshProUGUI>();
            if (numberText == null)
            {
                Debug.LogError("找不到Nums对象上的TextMeshProUGUI组件！");
            }
        }
        else
        {
            Debug.LogError("找不到名为Nums的游戏对象！");
        }
        
        if (frameAnimationController == null)
        {
            frameAnimationController = FindObjectOfType<FrameAnimationController>();
            if (frameAnimationController == null)
            {
                Debug.LogWarning("找不到FrameAnimationController组件！帧动画功能将被禁用。");
            }
        }
        // 初始化Image移动相关组件
        InitializeImageMovement();
    }

    /// <summary>
    /// 初始化Image移动相关组件和参数
    /// </summary>
    private void InitializeImageMovement()
    {
        if (movingImage != null)
        {
            imageRectTransform = movingImage.GetComponent<RectTransform>();
            parentCanvas = movingImage.GetComponentInParent<Canvas>();
            
            if (parentCanvas != null)
            {
                RectTransform canvasRect = parentCanvas.GetComponent<RectTransform>();
                canvasWidth = canvasRect.rect.width;
                Debug.Log("Canvas宽度: " + canvasWidth);
            }
            else
            {
                Debug.LogError("找不到父级Canvas！Image移动功能将被禁用。");
                enableImageMovement = false;
            }
        }
        else
        {
            Debug.LogWarning("未指定movingImage！Image移动功能将被禁用。");
            enableImageMovement = false;
        }
        
        currentSpeed = moveSpeed;
        lastKeyPressTime = Time.time;
    }
    void OnDestroy()
    {
        UninstallHook();
    }
    
    // 将虚拟键码转换为按键名称
    private string GetKeyName(int vkCode)
    {
        if (KeyCodeNames.TryGetValue(vkCode, out string keyName))
        {
            return keyName;
        }
        return $"Unknown Key ({vkCode})";
    }
    
    private void OnKeyPressed(int vkCode)
    {
        string keyName = GetKeyName(vkCode);
        
        // 设置TextMeshPro文字内容
        if (numberText != null)
        {
            numberText.text = (num++).ToString();
        }
        if (frameAnimationController != null)
        {

            frameAnimationController.NextFrame();
            Debug.Log("动画帧信息: " + frameAnimationController.GetFrameInfo());
        }
        // Image移动逻辑
        if (enableImageMovement && imageRectTransform != null)
        {
            MoveImageRight();
        }
        if (vkText != null)
        {
            vkText.text = keyName;
        }
    }
    private void MoveImageRight()
    {
        float currentTime = Time.time;
        
        // 根据打字速度调整移动速度
        if (adaptiveSpeed)
        {
            float timeSinceLastKey = currentTime - lastKeyPressTime;
            
            if (timeSinceLastKey < 0.1f) // 快速打字
            {
                currentSpeed = Mathf.Lerp(currentSpeed, maxMoveSpeed, 0.3f);
            }
            else if (timeSinceLastKey > 0.5f) // 慢速打字
            {
                currentSpeed = Mathf.Lerp(currentSpeed, minMoveSpeed, 0.3f);
            }
            
            currentSpeed = Mathf.Clamp(currentSpeed, minMoveSpeed, maxMoveSpeed);
        }
        else
        {
            currentSpeed = moveSpeed;
        }
        
        lastKeyPressTime = currentTime;
        
        // 获取当前位置
        Vector3 currentPosition = imageRectTransform.anchoredPosition;
        
        // 向右移动
        currentPosition.x += currentSpeed;
        
        // 检查是否超出右边界
        float imageWidth = imageRectTransform.rect.width;
        float rightBoundary = canvasWidth / 2f; // Canvas右边界
        
        if (currentPosition.x > rightBoundary + imageWidth / 2f)
        {
            // 移动到最左边
            currentPosition.x = -canvasWidth / 2f - imageWidth / 2f;
            Debug.Log("Image已移动到最左边重新开始");
        }
        
        // 应用新位置
        imageRectTransform.anchoredPosition = currentPosition;
        
        Debug.Log($"Image移动: 位置={currentPosition.x:F1}, 速度={currentSpeed:F1}");
    }
}
